package cn.wolfcode.wechat.service.impl;

import cn.wolfcode.wechat.domain.Account;
import cn.wolfcode.wechat.domain.Client;
import cn.wolfcode.wechat.mapper.ClientMapper;
import cn.wolfcode.wechat.query.ClientQueryObject;
import cn.wolfcode.wechat.service.IAccountService;
import cn.wolfcode.wechat.service.IClientService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

@Service
public class ClientServiceImpl implements IClientService {

    @Autowired
    private ClientMapper clientMapper;
    @Autowired
    private IAccountService accountService;

    @Override
    public void save(Client client) {
        Client oldClient = this.selectByOpenid(client.getOpenid());
        // 以前关注过测试号,则修改状态码以及最后关注的时间,并更新其他的信息
        if(oldClient != null){
            oldClient.setSubscribe(1);
            oldClient.setSubscribe_time(new Date().getTime());
            oldClient.setCity(client.getCity());
            oldClient.setCountry(client.getCountry());
            oldClient.setLanguage(client.getLanguage());
            oldClient.setNickname(client.getNickname());
            oldClient.setProvince(client.getProvince());
            oldClient.setSex(client.getSex());
            clientMapper.update(oldClient);
        }else {
            clientMapper.save(client);
            Account account = new Account();
            account.setId(client.getId());
            accountService.save(account);
        }
    }

    @Override
    public void update(Client client) {
        clientMapper.update(client);
    }

    @Override
    public Client get(Long id) {
        return clientMapper.get(id);
    }

    @Override
    public Client selectByOpenid(String openid) {
        return clientMapper.selectByOpenid(openid);
    }

    @Override
    public void unsubscribe(Client client) {
        Client oldClient = this.selectByOpenid(client.getOpenid());
        oldClient.setSubscribe(0);
        // 将状态码修改成未关注
        clientMapper.update(oldClient);
    }

    @Override
    public PageInfo query(ClientQueryObject qo) {
        PageHelper.startPage(qo.getCurrentPage(),qo.getPageSize());
        List<Client> queryPage = clientMapper.queryPage(qo);
        return new PageInfo(queryPage);
    }
}
